package com.haozi.reggie.controller;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.haozi.reggie.common.R;
import com.haozi.reggie.entity.User;
import com.haozi.reggie.service.UserService;
import com.haozi.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;



    /**
     * 发送短信验证码
     * @param user
     * @param session
     * @return
     * @throws ClientException
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)) {
            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码：{}",code);
            //发送短信
            //SMSUtils.sendMessage("签名","模板ID",phone,"");
            //将验证码存session
            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }
        return R.error("请输入手机号");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session) {

        //获取传过来的手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //校验验证码是否正确
        Object codeInSion = session.getAttribute(phone);
        if(!(codeInSion != null && codeInSion.equals(code))) {
            return R.error("验证码不正确");
        }

        //判断手机号是否存在 不存在就插入
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(userLambdaQueryWrapper);
        if(user == null) {
            //插入
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //登录成功写入sion
        session.setAttribute("user",user.getId());
        return R.success(user);
    }

    /**
     * 登出
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("登出成功");
    }
}
